from django.db import models

# Create your models here.
from goods.models import Goods
from user.models import User


class CartManager(models.Manager):
    def update_or_create(self, quantity=1, **kwargs):
        cart, created = self.get_or_create(**kwargs)
        if created:
            # 新建
            cart.quantity = quantity
        else:
            # 获取
            cart.quantity += quantity
        cart.sub_total = cart.quantity*cart.book.price
        cart.save()
        return cart, created

    def user_sub_total(self, user=None):
        total = 0
        quantity = 0
        cart = Cart.objects.filter(user=user)
        for item in cart:
            total += item.sub_total
            quantity += item.quantity
        return total, quantity


class Cart(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户',)
    good = models.ForeignKey(Goods, on_delete=models.CASCADE, null=True, verbose_name='商品')
    quantity = models.IntegerField('商品的数量', default=1)
    sub_total = models.DecimalField('总价', max_digits=8, decimal_places=2, default=0)
    checked = models.BooleanField('记录该条购物车是否被选中', default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    objects = CartManager()

    def __str__(self):
        return "{}的购物车".format(self.user.username)

    class Meta:
        # 联合唯一性约束
        unique_together = ['user', 'good']

